package com.jiezuo.flowable.listener;

import cn.hutool.core.collection.CollectionUtil;
import com.jiezuo.common.exception.BusinessRuntimeException;
import com.jiezuo.common.utils.SpringUtil;
import com.jiezuo.flowable.mapper.CommonMapper;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.flowable.engine.impl.context.Context;
import org.flowable.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class ContractRefundListener implements ExecutionListener {


    @Autowired
    CommonMapper commonMapper;

    @Override
    public void notify(DelegateExecution execution) {
        String eventName = execution.getEventName();
        String processInstanceId = execution.getProcessInstanceId();
        CommonMapper commonMapper = SpringUtil.getObject(CommonMapper.class);
        RuntimeService runtimeService = Context.getProcessEngineConfiguration().getRuntimeService();
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
        String startUserId = processInstance.getStartUserId();//申请人
        Map<String,Object> map = commonMapper.findSectionByStartUserId(startUserId);
        String division = String.valueOf(map.get("division"));
        if("1".equals(division)){
            execution.setVariable("i", 1);
            //还要去把对应事业部的院长查出来
            List<String> list = commonMapper.findBussinessByUserId(startUserId);
            if(!CollectionUtil.isEmpty(list)){
                String join = String.join(",", list);
                execution.setVariable("dean", join);
            }else{
                throw  new BusinessRuntimeException("请设置事业部院长");
            }
        }else{
            execution.setVariable("i", 2);
        }
    }
}
